遗传算法求f(x)=x1^2+x2^2最大值,其中0<=x1,x2<=7。
//this program uses SGA to calculate the maximum value of f(x) = x1^2 + x2^2
#include <iostream>
#include <ctime>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#define LENGTH 3
using namespace std;
class chromosome
{
public:
int x1,x2;
int value;
double fitness;
void assign(int a,int b)
{
x1 = a;
x2 = b;
cal_value();
}
void cal_value()
{
value = x1 << LENGTH;
value |= x2;
}
void cal_fitness()
{
fitness = x1*x1 + x2*x2;
}
};
double total_fitness = 0;
vector<chromosome> population[2];
vector<chromosome> temp;
int cop_counter = 0;
int selector = 0;
int and1 = ((1 << LENGTH) - 1) << LENGTH;
int and2 = (1 << LENGTH) - 1;
int variation_percent = 2;
int random(int end)
{
r